package com.iamback.dy.examine.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import com.iamback.dy.entity.Role;
import com.iamback.dy.entity.User;
import com.iamback.dy.entity.UserAssign;
import com.iamback.dy.entity.UserRole;
import com.iamback.dy.examine.common.Page;
import com.iamback.dy.examine.common.utils.MD5Utils;
import com.iamback.dy.examine.service.IResourceService;
import com.iamback.dy.examine.service.IRoleService;
import com.iamback.dy.examine.service.IUserService;
import com.iamback.dy.examine.vo.UserAssignView;
import com.iamback.dy.mapper.RoleMapper;
import com.iamback.dy.mapper.UserAssignMapper;
import com.iamback.dy.mapper.UserMapper;
@Service
public class UserServiceImpl implements IUserService{
   
    @Autowired
	private UserMapper userMapper;
	@Autowired
	private RoleMapper roleMapper;
	
	@Autowired
	private UserAssignMapper assignMapper;
	@Autowired
	private IRoleService roleService;
	@Override
	public User findByUserName(String username) {
		return userMapper.getUserByName(username);
	}
	
	@Override
	public Page<User> findUserPage(String searchText,Integer pageNum,Integer numPerPage){
		Map<String, Object> map = new HashMap<String, Object>();
		int start = pageNum ==0?0:(pageNum-1)*numPerPage;
		map.put("userName", searchText);
		map.put("pageNum", start);
		map.put("numPerPage", numPerPage);
		Page<User> page= new Page<User>(); 
		Integer count =userMapper.findUserPageCount(map);
	    if(count !=null && count>0) {
	    	List<User> users=userMapper.findUserPage(map);
	    	List<User> users2 =new ArrayList<User>();
	    	for(User user:users){ 
	    		Set<Role> roles=roleService.getRoleList(user.getId());
	    		user.setRoles(roles);
	    		users2.add(user);
	    	}
	    	page.setContent(users2);
	    	page.setTotalElements(count);
	    }else{
	    	page.setTotalElements(0);
	    }
		return page;
	}
	
	
	@Override
	public Page<UserAssignView> getUserAssignPage(Integer pageNum ,Integer numPerPage){
		Map<String, Object> map = new HashMap<String, Object>();
		int start = pageNum ==0?0:(pageNum-1)*numPerPage;
		map.put("pageNum", start);
		map.put("numPerPage", numPerPage);
		Page<UserAssignView> page= new Page<UserAssignView>(); 
		Integer count =userMapper.findUserPageCount(map);
		if(count!= null &&count>0){
			List<User> users = userMapper.findUserPage(map);
			List<UserAssignView> assignViews= new ArrayList<UserAssignView>();
			for(User user:users){
				UserAssignView assignView =new UserAssignView();
				UserAssign userAssign=assignMapper.getUserAssignByUserId(user.getId());
				assignView.setUserId(user.getId());
				assignView.setUserName(user.getUserName());
				if(userAssign !=null){
					assignView.setAssignId(userAssign.getId());
					assignView.setAssignType(userAssign.getAssignType());
				}
				assignViews.add(assignView);
			}
			page.setTotalElements(count);
			page.setContent(assignViews);
		}else{
			page.setTotalElements(0);
		}
		return page;
	}
	
	
	
	
	@Override
	public void updateUserAssign(UserAssign userAssign){
		if(userAssign.getId()!=null){
			assignMapper.updateUserAssign(userAssign);
		}else{
			assignMapper.insertUserAssign(userAssign);
		}
	}
	
	
	@Override
	public void saveOrUpdate(User user) {
		User dbUser = findByUserName(user.getUserName());
		if(user.getId() !=null &&user.getId()!=0){
			if(!user.getUserName().equals(dbUser.getUserName())||dbUser.getId()==user.getId()){ 
				userMapper.updateUserById(user);
			}else{
				Assert.state(false,"用户名不能出现重复");
			} 
		}else{
			if(!user.getUserName().equals(dbUser.getUserName())){
				user.setCreateTime(new Date());
				user.setUpdateTime(new Date());
				user.setDeleteStatus(0);
				user.setPassword(MD5Utils.md5("111111"));
				userMapper.addUser(user);
			}else{
				Assert.state(false,"用户名不能出现重复");
			}
		} 
	}
	
	@Override
	public void delete(Integer id) {
		User user =userMapper.getUserById(id);
		Assert.state(!"admin".equals(user.getUserName()),"超级管理员用户不能删除");
		Map<String, Object> map =new HashMap<String, Object>();
		map.put("userId", id);
		userMapper.deleteUserRole(map);
		userMapper.deleteUserById(id);
	}


	@Override
	public void grant(Integer id, String[] roleIds) {
		User user = userMapper.getUserById(id);
		Assert.notNull(user, "用户不存在");
		Assert.state(!"admin".equals(user.getUserName()),"超级管理员用户不能修改管理角色");
        List<UserRole> userRoles =new ArrayList<UserRole>();
		if(roleIds != null){
			for (int i = 0; i < roleIds.length; i++) {
				Integer rid = Integer.parseInt(roleIds[i]);
				Role role = roleMapper.findRoleById(rid);
				if(role !=null){
				UserRole userRole =new UserRole();
				userRole.setRoleId(rid);
				userRole.setUserId(id);
				userRoles.add(userRole);
				}
			}
			Map<String, Object> map =new HashMap<String, Object>();
			map.put("userId", id);
			userMapper.deleteUserRole(map);
			userMapper.saveUserRole(userRoles);
		}
	}

	@Override
	public User findUserById(Integer userId){
		User user = userMapper.getUserById(userId);
		Set<Role> roles=roleService.getRoleList(user.getId());
		user.setRoles(roles);
		return user;
	}
}
